package com.alit.xiaoitts;

import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;

import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class XiaoiTTSService {

	private String ttsUrl;

	public XiaoiTTSService(String ttsUrl) {
		this.ttsUrl = ttsUrl;
	}

	/**
	 * @param ttsTxt
	 *          输入TTS的文本
	 * @param voice
	 *          Mei-Jia/Bin-Bin/Li-Li/Li-Mei/Tian-Tian/Sin-Ji
	 * @param format
	 *          PCM/SPX
	 * @param os
	 *          输出流
	 */
	public void doTts(final String ttsTxt, String voice, String format, final OutputStream os,
			final TTsConsumer tTsConsumer) throws Exception {

		final CountDownLatch latch = new CountDownLatch(1);

		XiaoiTTSConnector connector = new XiaoiTTSConnector();
		connector.connect(ttsUrl);

		String message1 = BEGIN_TTS(voice, format);
		System.out.println("out_json = " + message1);
		connector.sendText(message1);
		connector.addListener(new WebSocketAdapter() {
			@Override
			public void onTextMessage(WebSocket websocket, String text) throws Exception {
				String msgSend = null;

				if (text.startsWith("BEGIN_TTS_R")) {
					msgSend = "TTS_TEXT:" + ttsTxt + "";
				} else if (text.startsWith("TTS_TEXT_R")) {
					if (tTsConsumer != null) {
						tTsConsumer.consumer(text);
					}
					msgSend = "STOP_TTS";
				}

				if (msgSend != null) {
					System.out.println("out_json = " + msgSend);
					websocket.sendText(msgSend);
				}
			}

			@Override
			public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
				// logger.info("in_binary length= " + binary.length);
				if (binary.length > 0) {
					byte flag = binary[binary.length - 1];
					os.write(binary, 0, binary.length - 1);
					os.flush();

					// C <- S = Data[0 ~ n bytes] + flag(byte) (flag(0):Continue, flag(1):End Of
					// Data, flag(2):Internal Error)
					if (flag != 0) {
						// logger.info("in_binary end ");
						latch.countDown();
					}
				}
			}
		});

		try {
			latch.await(60 * 5, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		connector.disconnect();
	}

	private String BEGIN_TTS(String voice, String format) {
		return "BEGIN_TTS:" + format + ":" + voice;
	}

}
